package DbToExcel;

import POJO.DbMoudle;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.bson.Document;


import java.io.*;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;

public class Main {

    //Logger logger;
    static MongoCollection collection;
    static String BASE_OUT_PUT_PATH;

    public static void main(String[] args) throws Exception {
        DbMoudle dbMoudle = new DbMoudle();
        dbMoudle.setAddress("192.168.1.173");
        dbMoudle.setPort("27017");
        dbMoudle.setDbName("天气");
        dbMoudle.setCollection("机场id表");
        START(dbMoudle);
    }

    public static void START(DbMoudle dbMoudle) throws Exception {
        initialization(dbMoudle);
        FindIterable<Document> documents = collection.find();

        WriteToExcel(documents, dbMoudle.getCollection());
    }

    public static void initialization(DbMoudle dbMoudle) throws Exception {
        /**
         * 初始化环境：
         * 1. 检查db相关信息是否正常
         * 2. 读取myProperties文件， 初始化部分变量
         */
        //logger = LoggerFactory.getLogger(Main.class);
        try{
            MongoClient client =  new MongoClient(dbMoudle.getAddress(), Integer.valueOf(dbMoudle.getPort()));
            MongoDatabase mongoDatabase= client.getDatabase(dbMoudle.getDbName());
            collection = mongoDatabase.getCollection(dbMoudle.getCollection());
        }catch (Exception e){
            e.printStackTrace();
            //logger.warn("collection 初始化错误");
            throw new Exception("collection 初始化错误，请检查信息输入是否有误！");
        }

        // 将配置文件加载到流中
        InputStream in = Main.class.getClassLoader().getResourceAsStream("myProperties.properties");
        // 创建并加载配置文件
        Properties pro = new Properties();
        pro.load(in);
        BASE_OUT_PUT_PATH = pro.getProperty("base_out_put_path");
    }



    public static void WriteToExcel(FindIterable<Document> documents, String excelName) throws Exception {
        //logger.info(excelName + ".xlsx 开始写入" );
        Set<String> set_list = new LinkedHashSet<>();
        for (Document document : documents){
            set_list.addAll(document.keySet());
        }

        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        Row row = sheet.createRow(0);
        int index = 0;
        int n = set_list.size();
        for (String key : set_list)
            row.createCell(index++).setCellValue(key);

        int rownum = 1;
        int count = 0;
        for (Document document : documents) {
            int cellnum = 0;

            count++;
            Row row1 = sheet.createRow(rownum++);
            for (String key : set_list){
                try {
                    row1.createCell(cellnum++).setCellValue(document.get(key).toString());
                }
                catch (Exception e){
                    row1.createCell(cellnum++).setCellValue("");
                }

            }

            System.out.println("Writing to the excel ------------------------------");
        }

        if (count == 0)
            throw new Exception("Number of item = 0;  check db info, or try again!");
        /**
         * 保存路径 默认为 tomcat的bin 文件夹下
         */
        String FilePath = BASE_OUT_PUT_PATH + excelName + "\\";
        Utils.initFolder(FilePath);
        workbook.write(new FileOutputStream( FilePath + excelName +".xlsx"));
        //logger.info("写入excel完毕*--------------------\n条目数量：" + count);
        System.out.println("End of writing to excel--------------------\nNumber of item：" + count);
    }

}
